package cn.db101.fairy.config

import cn.binarywang.wx.miniapp.api.WxMaService
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl
import org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

/**
 * @author zooy
 * @since 2024/7/10-16:29
 */
@Configuration
@MapperScan("cn.db101.fairy.mapper")
@EnableConfigurationProperties(FairyConfigProperties::class)
class FairyConfig: WebMvcConfigurer {

    @Bean
    fun wxMaService(fairyConfigProperties: FairyConfigProperties): WxMaService {

        return WxMaServiceImpl().also {
            it.wxMaConfig = WxMaDefaultConfigImpl().apply {
                appid = fairyConfigProperties.appId
                secret = fairyConfigProperties.appSecret
                msgDataFormat = "JSON"
            }
        }
    }

    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
            .allowedOriginPatterns("*")
            .allowedHeaders(
                "Content-Type",
                "X-Requested-With",
                "accept,Origin",
                "Access-Control-Request-Method",
                "Access-Control-Request-Headers",
                "token",
                "authorization",
                "Access-Control-Allow-Origin",
                "Access-Control-Allow-Credentials",
                "Cache-Control",
                "x-token"
            )
            .allowedMethods("*").allowCredentials(true)
    }

}
